`ifndef REGS_V
`define REGS_V


`include "defines.v"

module regs(
	input  wire clk,
	input  wire rstn,

	//from id
	input  wire[`RegAddrWidth - 1 : 0] 	reg1_raddr_i,
	input  wire[`RegAddrWidth - 1 : 0] 	reg2_raddr_i,
	
	//to id
	output reg[`RegDataWidth - 1 : 0] 	reg1_rdata_o,
	output reg[`RegDataWidth - 1 : 0] 	reg2_rdata_o,
	
	//from ex
	input wire[`RegAddrWidth - 1 : 0] 	waddr_i,
	input wire[`RegDataWidth - 1 : 0]	wdata_i,
	input 								wen_i

);

reg[`RegDataWidth - 1 : 0] GPR[0 : `RegNum - 1]; // regs: x0, x1, ..., x31

// 初始化和写数据
integer i;
always @(posedge clk or negedge rstn)begin
	if(rstn == 1'b0) begin
		for(i = 0; i < 32 ; i = i + 1) begin
			GPR[i] <= `REG_ZERO;
		end
	end	
	// 保护寄存器 x0
	else if((wen_i == 1'b1) && (waddr_i != `REG_X0_ADDR)) begin
		GPR[waddr_i] <= wdata_i;
	end	
end

// 读寄存器 1
always @(*) begin
	if(rstn == 1'b0) begin
		reg1_rdata_o = `REG_ZERO;
	end
	// 保护寄存器 x0
	else if(reg1_raddr_i == `REG_X0_ADDR) begin
		reg1_rdata_o = `REG_X0_DATA;
	end
	// 避免读写冲突
	else if((wen_i == 1'b1) && (reg1_raddr_i == waddr_i)) begin
		reg1_rdata_o = wdata_i;
	end
	else begin
		reg1_rdata_o = GPR[reg1_raddr_i];
	end
end

// 读寄存器 2
always @(*) begin
	if(rstn == 1'b0) begin
		reg2_rdata_o = `REG_ZERO;
	end
	// 保护寄存器 x0
	else if(reg2_raddr_i == `REG_X0_ADDR) begin
		reg2_rdata_o = `REG_X0_DATA;
	end
	// 避免读写冲突
	else if((wen_i == 1'b1) && (reg2_raddr_i == waddr_i)) begin
		reg2_rdata_o = wdata_i;
	end
	else begin
		reg2_rdata_o = GPR[reg2_raddr_i];
	end
end

endmodule


`endif // REGS_V